﻿
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;

namespace ConsoleWebApi.Authorization
{
    /// <summary>
    /// 不序列化属性协议
    /// </summary>
    public class HideAttrContractResolver : DefaultContractResolver
    {
        /// <summary>
        /// 初始化一个不序列化属性协议
        /// </summary>
        /// <param name="Propertys"></param>
        public HideAttrContractResolver(String[] Propertys)
        {
            HidePropertys = Propertys;
        }

        /// <summary>
        /// 要隐藏的属性名
        /// </summary>
        public String[] HidePropertys = new string[0];

        /// <summary>
        ///  http://james.newtonking.com/projects/json/help/index.html?topic=html/ContractResolver.htm
        /// </summary>
        /// <param name="member"></param>
        /// <param name="memberSerialization"></param>
        /// <returns></returns>
        protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
        {
            //创建规则属性
            JsonProperty p = base.CreateProperty(member, memberSerialization);
            //如果包含属性
            if (HidePropertys.Contains(p.PropertyName))
            {
                //决定是否序列化
                p.ShouldSerialize = instance =>
                {
                    return false;
                };
            }
            return p;
        }
    }
}